<template>
  <div class="app-container">
    <!-- 头部增加阴影和渐变背景 -->
    <el-header class="header">
      <div class="logo">
        <i class="el-icon-sunny logo-icon"></i>
        <span class="logo-text">农业大棚温度测量系统</span>
      </div>
    </el-header>

    <el-main class="main-content">
      <!-- 系统简介增加图标和排版优化 -->
      <div class="system-introduction card-container">
        <h2 class="section-title">
          <i class="el-icon-info"></i>
          系统简介
        </h2>
        <div class="intro-content">
          <p class="intro-item">
            <i class="el-icon-s-data"></i>
            本系统通过部署在大棚的高精度温度传感器，实时采集作物生长环境温度数据。
          </p>
          <p class="intro-item">
            <i class="el-icon-warning-outline"></i>
            当检测到温度超过预设阈值（过高/过低）时，系统将自动通过QQ邮件通知相关责任人。
          </p>
          <p class="intro-item">
            <i class="el-icon-s-marketing"></i>
            提供历史温度趋势分析，帮助农户优化种植策略，保障农作物最佳生长环境。
          </p>
        </div>
      </div>

      <!-- 图表容器增加边框和标题装饰 -->
      <div class="data-display card-container">
        <h2 class="section-title">
          <i class="el-icon-data-line"></i>
          实时温度监测曲线
        </h2>
        <div id="temperature-chart"></div>
      </div>

      <!-- 报警表格样式优化 -->
      <div class="alarm-display card-container">
        <h2 class="section-title">
          <i class="el-icon-bell"></i>
          实时报警信息
        </h2>
        <el-table
          :data="alarmData"
          style="width: 100%"
          stripe
          v-loading="loading"
          class="alarm-table">
          <el-table-column prop="greenhouseName" label="大棚名称" width="180">
            <template #default="{row}">
              <i class="el-icon-office-building"></i>
              {{ row.greenhouseName }}
            </template>
          </el-table-column>
          <el-table-column prop="alarmMessage" label="报警详情">
            <template #default="{row}">
              <el-tag
                :type="row.temperatureValue > thresholdHigh ? 'danger' : 'primary'"
                effect="dark">
                {{ row.alarmMessage }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="alarmTime"
            label="报警时间"
            width="200"
            sortable>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';
import dayjs from "dayjs";

export default {
  data() {
    return {
      alarmData: [],
      chartData: {
        xData: [],    // 存储原始时间字符串
        yData: []     // 存储温度值
      },
      chartInstance: null
    };
  },
  mounted() {
    this.initChart();
    this.fetchTemperatureData();
    this.fetchAlarmData();
    setInterval(() => this.fetchTemperatureData(), 5000);
  },
  methods: {
    initChart() {
      const chartDom = document.getElementById('temperature-chart');
      this.chartInstance = echarts.init(chartDom);
      window.addEventListener('resize', () => this.chartInstance.resize());
    },

    async fetchAlarmData() {
      try {
        const response = await axios.get('/dev-api/system/log/current');
        if (response.data.code === 200) {
          this.alarmData = response.data.data.map(item => ({
            ...item,
            alarmTime: dayjs(item.alarmTime).format('YYYY-MM-DD HH:mm:ss')
          }));
        }
      } catch (error) {
        console.error('获取报警数据失败:', error);
      }
    },

    async fetchTemperatureData() {
      try {
        const response = await axios.get('/dev-api/system/temperature/real-time-with-name');
        if (response.data.code === 200) {
          this.processChartData(response.data.data);
        }
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    },

    processChartData(rawData) {
      // 直接使用原始时间字符串
      this.chartData.xData = rawData.map(item => item.recordTime);
      this.chartData.yData = rawData.map(item => item.temperatureValue);

      // 调试输出
      console.log('当前数据:',
        rawData.map(item => ({
          time: item.recordTime,
          value: item.temperatureValue
        }))
      );

      this.updateChart();
    },

    updateChart() {
      const option = {
        title: { text: '大棚温度动态曲线', left: 'center' },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            return `时间：${params[0].name}<br/>温度：${params[0].value}℃`;
          }
        },
        xAxis: {
          type: 'category',
          data: this.chartData.xData,
          axisLabel: {
            show: true,
            interval: 0, // 强制显示所有标签
            rotate: 45,
            formatter: (value) => value // 直接显示原始字符串
          }
        },
        yAxis: {
          type: 'value',
          name: '温度 (℃)'
        },
        series: [{
          name: '温度',
          type: 'line',
          showSymbol: true,
          symbolSize: 8,
          data: this.chartData.yData,
          lineStyle: { width: 2, color: '#409EFF' },
          itemStyle: { color: '#409EFF' }
        }],
        dataZoom: [{
          type: 'slider',
          show: true,
          xAxisIndex: 0,
          start: 0,
          end: 100,
          bottom: 20,
          height: 20
        }]
      };

      this.chartInstance.setOption(option, true);
    }
  }
};
</script>

<style scoped>
/* 统一配色方案 */
:root {
  --primary-color: #409EFF;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
}

.app-container {
  background: #f8f9fa;
  min-height: 100vh;
}

/* 头部样式优化 */
.header {
  background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
  box-shadow: 0 2px 12px rgba(0,0,0,.1);
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 32px;
  color: var(--success-color);
}

.logo-text {
  font-size: 24px;
  font-weight: 600;
  letter-spacing: 1px;
  background: linear-gradient(45deg, #fff 0%, #e6f7ff 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 通用卡片样式 */
.card-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  margin-bottom: 24px;
  padding: 24px;
  transition: transform 0.3s;
}

.card-container:hover {
  transform: translateY(-2px);
}

/* 区块标题样式 */
.section-title {
  color: #303133;
  font-size: 20px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f2f5;
}

/* 系统简介排版优化 */
.intro-content {
  display: grid;
  gap: 16px;
  padding: 0 16px;
}

.intro-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  color: #606266;
  line-height: 1.8;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
  transition: background 0.3s;
}

.intro-item:hover {
  background: #f0f7ff;
}

.intro-item i {
  font-size: 18px;
  color: var(--primary-color);
  margin-top: 4px;
}

/* 图表容器优化 */
#temperature-chart {
  width: 100%;
  height: 600px;
  margin: 20px 0;
}

/* 报警表格样式优化 */
.alarm-table {
  border-radius: 8px;
  overflow: hidden;
}

.alarm-table::before {
  display: none;
}

.alarm-table >>> .el-table__header th {
  background: #f8fafc;
  font-weight: 600;
}

.alarm-table >>> .el-table__row:hover td {
  background: #f0f7ff !important;
}
</style>
